<template>
  <section class="design-container-root cursor-resize" v-bind="$attrs"
           :style="style"
           :data-rotation="appStore.dataRotation">
    <aside class="my-aside display-flex-column" style="border-right: 1px #e9e9e9 solid; background: #f8f8f8">
      <widget :module-name="props.module?.name" :showBackButton="showBackButton" @back="back" />
    </aside>
    <main class=" my-main design-container-root_main">
      <PanelView :designProps="props" />
    </main>
  </section>
  <my-mouse-tips />
</template>

<script setup lang="ts">
import widget from '@myprint/design/components/content/widget/index.vue';
import PanelView from '@myprint/design/components/content/panel/index.vue';
import { computed, CSSProperties, onMounted, onUnmounted, reactive, Ref, ref, watch } from 'vue-demi';
import { Panel, Provider, RuntimeElementOption } from '@myprint/design/types/entity';
import { mitt, to } from '@myprint/design/utils/utils';
import { ActionEnum, init, record, Snapshot } from '@myprint/design/utils/historyUtil';
// @ts-ignore
import { Module, SaveResult, Template } from '@myprint/design/types/R';
import { useAppStoreHook } from '@myprint/design/stores/app';
import MyMouseTips from '@myprint/design/components/my/mouse-tips/my-mouse-tips.vue';
import {
  defaultPreviewData,
  initPanel,
  parentInitElement,
  setCurrentPanel,
  setPreviewData,
  setProvider
} from '@myprint/design/utils/elementUtil';
import { newSelecto } from '@myprint/design/plugins/moveable/selecto';
import { MyMessage } from '@myprint/design/components/my/message/my-message';
import { MyPrinter } from '@myprint/design/printer';
import { i18n } from '@myprint/design/locales';
import { mountedKeyboardEvent, unMountedKeyboardEvent } from '@myprint/design/utils/keyboardUtil';

// todo 添加页面旋转功能，表格添加表头功能，excel表格导入功能，markdown表格粘贴功能，bug对齐功能点击对齐后点击面板元素回原问题，bug自动宽度无限变宽问题
const appStore = useAppStoreHook();

const $emit = defineEmits<{
  (e: 'back'): void;
  (e: 'panelImg', blobList: Blob[]): void;
}>();

const data = reactive({
  buildImgIs: false
});

const provider = ref({}) as Ref<Provider>;
const panel = reactive({
  runtimeOption: {
    dragInIs: false
  },
  type: 'Panel',
  dragSnapPanelIs: 1,
  dragSnapIs: 1
}) as Panel;
const previewData = ref<any[]>([]);
setCurrentPanel(panel);

const props = withDefaults(defineProps<{
  module?: Module;
  template?: Template;
  height?: string;
  saveTemplate?: (template: Template) => Promise<SaveResult>;
  generateImg?: boolean;
  showBackButton?: boolean;
  showPrintButton?: boolean;
  showDownloadPdfButton?: boolean;
  showPreviewButton?: boolean;
  showClearButton?: boolean;
  showSaveButton?: boolean;
}>(), {
  showBackButton: false,
  showPrintButton: true,
  showDownloadPdfButton: true,
  showPreviewButton: true,
  showClearButton: true,
  showSaveButton: true
});

const style = computed(() => {
  return <CSSProperties>{
    height: props.height
  };
});

onMounted(() => {
  // mitt.on('saveTemplate', saveTemplate);
  initModule();
  initTemplate();
  newSelecto();
});

onUnmounted(() => {
  // mitt.off('saveTemplate', saveTemplate);
});

watch(() => props.module, (_n, _o) => {
    if (props.module) {
      initModule();
    }
  }, { deep: true } // 🔑 深度监听
);

function initModule() {
  if (!props.module) {
    return;
  }
  provider.value = JSON.parse(props.module.provider!);
  previewData.value = JSON.parse(props.module.previewData!);
  setPreviewData(previewData.value);
  setProvider(provider.value);
  initPanel(panel, provider);
  setCurrentPanel(panel);
}

const templateWatchStop = watch(() => props.template, (_n, _o) => {
  if (props.template) {
    initTemplate();
    templateWatchStop();
  }
});

function initTemplate() {
  if (!props.template) {
    return;
  }
  to(JSON.parse(props.template.content), panel);
  setCurrentPanel(panel);

  // initPanel();

  if (!panel.watermarkContent) {
    // panel.watermarkContent = 'my-print';
  }
  if (!panel.groupList) {
    panel.groupList = [];
  }
  if (!panel.auxiliaryLineList) {
    panel.auxiliaryLineList = [];
  }
  for (let myAuxiliaryLine of panel.auxiliaryLineList) {
    myAuxiliaryLine.runtimeOption = { x: 0, y: 0, auxiliaryLineStatus: 'SHOW' } as RuntimeElementOption;
  }
  panel.runtimeOption = {} as any;

  // console.log(JSON.parse(JSON.stringify(panel.elementList[0])))
  // for (let i = 0; i < 1000; i++) {
  //   const  tmp = JSON.parse(JSON.stringify(panel.elementList[0]))
  //   tmp.y = tmp.y + 0.2
  //   // panel.elementList?.unshift(tmp)
  //
  // }
  for (let i = 0; i < panel.elementList.length; i++) {
    const element = panel.elementList[i];
    parentInitElement(panel, panel, element, i);
  }
  panel.pageHeader && parentInitElement(panel, panel, panel.pageHeader, 0);
  panel.pageFooter && parentInitElement(panel, panel, panel.pageFooter, 0);

  init(panel.name);

  if (provider.value.pageUnit == undefined) {
    provider.value.pageUnit = 'px';
  }

  mitt.emit('updatePanel');
  mitt.emit('changePageSize');
}

function back() {
  $emit('back');
}

// todo 实现模板保存 暂定为保存为文件
// function saveTemplate() {
//   if (props.generateImg) {
//     if (!data.buildImgIs) {
//       data.buildImgIs = true;
//       MyPrinter.imgChrome({ previewDataList: [defaultPreviewData(previewData.value)[0]] })
//         .then(res => {
//           $emit('panelImg', res.blobList!);
//           data.buildImgIs = false;
//         }).catch(_e => {
//         data.buildImgIs = false;
//       });
//     }
//   }
//
//   const template = {} as Template;
//   template.name = panel.name;
//   template.content = JSON.stringify(panel, (key, value) => {
//     if ('runtimeOption' == key) return undefined;
//     return value;
//   });
//   if (props.saveTemplate != null) {
//     props.saveTemplate(template)
//       .then(_res => {
//         // 保存成功
//         MyMessage.success(i18n('common.save.success'));
//       }).catch(e => {
//       // 保存失败
//       let failMsg = i18n('common.save.fail');
//       if (e.msg) {
//         failMsg = failMsg + ': ' + e.msg;
//       }
//       MyMessage.success(failMsg);
//     });
//   }
// }

const setTemplate = (template: Template) => {
  let contentData: any;

  if (typeof template.content === 'string') {
    contentData = JSON.parse(template.content);
  } else {
    contentData = template.content;
  }

  to(contentData, panel);

  // 确保 panel 基本属性被正确初始化
  if (!panel.runtimeOption) {
    panel.runtimeOption = {
      dragInIs: false
    } as any;
  } else if (panel.runtimeOption.dragInIs === undefined) {
    panel.runtimeOption.dragInIs = false;
  }

  // 确保其他必要属性存在
  if (panel.type === undefined) {
    panel.type = 'Panel';
  }
  if (panel.dragSnapPanelIs === undefined) {
    panel.dragSnapPanelIs = 1;
  }
  if (panel.dragSnapIs === undefined) {
    panel.dragSnapIs = 1;
  }

  // 初始化元素列表中的每个元素
  if (panel.elementList && Array.isArray(panel.elementList)) {
    for (let i = 0; i < panel.elementList.length; i++) {
      const element = panel.elementList[i];
      parentInitElement(panel, panel, element, i);
    }
  }

  // 初始化页眉页脚
  if (panel.pageHeader) {
    parentInitElement(panel, panel, panel.pageHeader, 0);
  }
  if (panel.pageFooter) {
    parentInitElement(panel, panel, panel.pageFooter, 0);
  }

  setCurrentPanel(panel);
  mitt.emit('updatePanel');
  mitt.emit('changePageSize');

  // 记录操作
  record(<Snapshot>{
    type: 'PANEL',
    content: panel.name,
    action: ActionEnum.INIT,
    elementList: appStore.currentElement
  });
};

const getTemplate = () => {
  const template = {} as Template;
  template.name = panel.name;
  template.content = JSON.stringify(panel, (key, value) => {
    if ('runtimeOption' == key) return undefined;
    return value;
  });
  return template;
};

defineExpose({
  setTemplate,
  getTemplate,
  mountedKeyboardEvent,
  unMountedKeyboardEvent,
});
</script>
